const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const { doctorModel, hospitalModel } = require('../db/models/cosmetic');
const { ProductTypeModel } = require('../db/producttype');

// 医生头像上传目录配置
const avatarUploadRoot = path.join(__dirname, '..', 'uploads', 'avatar')
try {
  if (!fs.existsSync(avatarUploadRoot)) fs.mkdirSync(avatarUploadRoot, { recursive: true })
} catch (_) {}

// 医生头像存储配置
const avatarStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, avatarUploadRoot)
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname) || '.jpg'
    const filename = `doctor_avatar_${Date.now()}_${Math.floor(Math.random()*1e9)}${ext}`
    cb(null, filename)
  }
})

// 文件过滤器 - 只允许图片
const fileFilter = (req, file, cb) => {
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png']
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true)
  } else {
    cb(new Error('只支持 JPG、JPEG、PNG 格式的图片'), false)
  }
}

const avatarUpload = multer({ 
  storage: avatarStorage,
  limits: {
    fileSize: 2 * 1024 * 1024 // 2MB 限制
  },
  fileFilter: fileFilter
})

/**
 * 获取医生数量统计
 * GET /pcdoctor/count
 */
router.get('/count', async (req, res) => {
  try {
    const count = await doctorModel.countDocuments();
    
    res.json({
      success: true,
      message: '获取医生数量成功',
      data: {
        count
      }
    });
  } catch (error) {
    console.error('获取医生数量失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医生数量失败',
      error: error.message
    });
  }
});

/**
 * 获取医生列表
 * GET /pcdoctor/list
 * 查询参数:
 * - page: 页码 (默认1)
 * - limit: 每页数量 (默认10)
 * - category: 医生分类筛选
 * - specialty: 专业领域筛选
 * - city: 城市筛选
 * - province: 省份筛选
 * - isHot: 是否热门医生 (true/false)
 * - keyword: 搜索关键词 (医生姓名、医院名称、专业领域)
 * - sortBy: 排序方式 (viewCount: 按浏览量, createTime: 按创建时间)
 * - sortOrder: 排序顺序 (asc: 升序, desc: 降序, 默认desc)
 */
router.get('/list', async (req, res) => {
  try {
    const {
      page = 1,
      limit = 10,
      category,
      specialty,
      city,
      province,
      isHot,
      keyword,
      sortBy = 'createTime',
      sortOrder = 'desc'
    } = req.query;

    // 构建查询条件
    const query = {};
    
    if (category) query.category = category;
    if (specialty) query.specialties = { $in: [specialty] }; // 专业领域筛选
    if (city) query.city = city;
    if (province) query.province = province;
    if (isHot !== undefined) query.isHot = isHot === 'true';
    
    // 关键词搜索 - 支持医生姓名、医院名称、专业领域搜索
    if (keyword) {
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { hospital: { $regex: keyword, $options: 'i' } },
        { specialties: { $in: [new RegExp(keyword, 'i')] } }
      ];
    }

    // 构建排序条件
    const sort = {};
    sort[sortBy] = sortOrder === 'asc' ? 1 : -1;

    // 计算分页
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const skip = (pageNum - 1) * limitNum;

    // 执行查询
    const doctors = await doctorModel
      .find(query)
      .populate('hospitalId', 'name logo rating location category status') // 关联医院信息
      .sort(sort)
      .skip(skip)
      .limit(limitNum)
      .lean(); // 使用lean()提高查询性能

    // 获取总数
    const total = await doctorModel.countDocuments(query);

    // 计算分页信息
    const totalPages = Math.ceil(total / limitNum);
    const hasNextPage = pageNum < totalPages;
    const hasPrevPage = pageNum > 1;

    res.json({
      success: true,
      message: '获取医生列表成功',
      data: {
        doctors,
        pagination: {
          current: pageNum,
          limit: limitNum,
          total,
          totalPages,
          hasNextPage,
          hasPrevPage
        }
      }
    });

  } catch (error) {
    console.error('获取医生列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医生列表失败',
      error: error.message
    });
  }
});

/**
 * 获取医生详情
 * GET /pcdoctor/detail/:id
 */
router.get('/detail/:id', async (req, res) => {
  try {
    const { id } = req.params;

    const doctor = await doctorModel
      .findById(id)
      .populate('hospitalId', 'name logo rating location city province category status')
      .populate('products.id', 'title price originalPrice rating images category')
      .lean();

    if (!doctor) {
      return res.status(404).json({
        success: false,
        message: '医生不存在'
      });
    }

    // 增加浏览次数
    await doctorModel.findByIdAndUpdate(id, { $inc: { viewCount: 1 } });
    doctor.viewCount += 1;

    res.json({
      success: true,
      message: '获取医生详情成功',
      data: doctor
    });

  } catch (error) {
    console.error('获取医生详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医生详情失败',
      error: error.message
    });
  }
});

/**
 * 获取医生分类列表
 * GET /pcdoctor/categories
 */
router.get('/categories', async (req, res) => {
  try {
    const categories = await doctorModel.distinct('category');
    
    res.json({
      success: true,
      message: '获取医生分类成功',
      data: categories.filter(cat => cat) // 过滤掉空值
    });

  } catch (error) {
    console.error('获取医生分类失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医生分类失败',
      error: error.message
    });
  }
});

/**
 * 获取城市列表
 * GET /pcdoctor/cities
 */
router.get('/cities', async (req, res) => {
  try {
    const { province } = req.query;
    
    const query = province ? { province } : {};
    const cities = await doctorModel.distinct('city', query);
    
    res.json({
      success: true,
      message: '获取城市列表成功',
      data: cities.filter(city => city) // 过滤掉空值
    });

  } catch (error) {
    console.error('获取城市列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取城市列表失败',
      error: error.message
    });
  }
});

/**
 * 获取省份列表
 * GET /pcdoctor/provinces
 */
router.get('/provinces', async (req, res) => {
  try {
    const provinces = await doctorModel.distinct('province');
    
    res.json({
      success: true,
      message: '获取省份列表成功',
      data: provinces.filter(province => province) // 过滤掉空值
    });

  } catch (error) {
    console.error('获取省份列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取省份列表失败',
      error: error.message
    });
  }
});

/**
 * 获取医院列表
 * GET /pcdoctor/hospitals
 */
router.get('/hospitals', async (req, res) => {
  try {
    const hospitals = await hospitalModel
      .find({ status: 'active' }, 'name _id category city province rating')
      .sort({ name: 1 })
      .lean();
    
    res.json({
      success: true,
      message: '获取医院列表成功',
      data: hospitals
    });

  } catch (error) {
    console.error('获取医院列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医院列表失败',
      error: error.message
    });
  }
});

/**
 * 获取专业领域选项（产品分类）
 * GET /pcdoctor/specialties
 */
router.get('/specialties', async (req, res) => {
  try {
    const specialties = await ProductTypeModel
      .find({}, 'name')
      .sort({ name: 1 })
      .lean();
    
    // 转换为字符串数组
    const specialtyNames = specialties.map(item => item.name);
    
    res.json({
      success: true,
      message: '获取专业领域选项成功',
      data: specialtyNames
    });

  } catch (error) {
    console.error('获取专业领域选项失败:', error);
    res.status(500).json({
      success: false,
      message: '获取专业领域选项失败',
      error: error.message
    });
  }
});

/**
 * 更新医生信息
 * PUT /pcdoctor/update/:id
 */
router.put('/update/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    // 验证必填字段
    const requiredFields = ['name', 'hospital', 'province', 'city', 'category', 'specialties'];
    for (const field of requiredFields) {
      if (!updateData[field]) {
        return res.status(400).json({
          success: false,
          message: `${field} 是必填字段`
        });
      }
    }

    // 验证专业领域是否为数组
    if (!Array.isArray(updateData.specialties)) {
      return res.status(400).json({
        success: false,
        message: '专业领域必须是数组格式'
      });
    }

    // 验证专业领域数量限制
    if (updateData.specialties.length > 2) {
      return res.status(400).json({
        success: false,
        message: '每个医生最多只能有2个专业领域'
      });
    }

    // 检查医生是否存在
    const existingDoctor = await doctorModel.findById(id);
    if (!existingDoctor) {
      return res.status(404).json({
        success: false,
        message: '医生不存在'
      });
    }

    // 处理医院ID更新
    let hospitalId = existingDoctor.hospitalId; // 默认保持原有的hospitalId
    
    // 如果前端直接提供了hospitalId，优先使用前端提供的
    if (updateData.hospitalId !== undefined) {
      hospitalId = updateData.hospitalId || null;
    } 
    // 否则根据医院名称查找医院ID（向后兼容）
    else if (updateData.hospital && updateData.hospital !== existingDoctor.hospital) {
      const hospital = await hospitalModel.findOne({ 
        name: updateData.hospital,
        status: 'active'
      });
      if (hospital) {
        hospitalId = hospital._id;
      } else {
        // 如果找不到对应的医院，将hospitalId设为null
        hospitalId = null;
      }
    }

    // 更新医生信息
    const updatedDoctor = await doctorModel.findByIdAndUpdate(
      id,
      {
        $set: {
          name: updateData.name,
          hospital: updateData.hospital,
          hospitalId: hospitalId,
          province: updateData.province,
          city: updateData.city,
          category: updateData.category,
          avatar: updateData.avatar || existingDoctor.avatar,
          specialties: updateData.specialties,
          tag: updateData.tag || existingDoctor.tag,
          isHot: updateData.isHot !== undefined ? updateData.isHot : existingDoctor.isHot
        }
      },
      { new: true, runValidators: true }
    ).populate('hospitalId', 'name logo rating location category status');

    res.json({
      success: true,
      message: '医生信息更新成功',
      data: updatedDoctor
    });

  } catch (error) {
    console.error('更新医生信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新医生信息失败',
      error: error.message
    });
  }
});

/**
 * 医生头像上传接口
 * POST /pcdoctor/upload-avatar
 */
router.post('/upload-avatar', avatarUpload.single('file'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ 
        success: false, 
        message: '未接收到文件' 
      })
    }
    
    const relativeUrl = `/uploads/avatar/${req.file.filename}`
    const fullUrl = `${req.protocol}://${req.get('host')}${relativeUrl}`
    
    res.json({ 
      success: true, 
      message: '头像上传成功',
      data: { 
        url: relativeUrl,
        fullUrl: fullUrl,
        filename: req.file.filename,
        size: req.file.size,
        mimetype: req.file.mimetype
      } 
    })
  } catch (error) {
    console.error('头像上传失败:', error)
    res.status(500).json({ 
      success: false, 
      message: '头像上传失败', 
      error: error.message 
    })
  }
})

/**
 * 删除头像文件
 * DELETE /pcdoctor/delete-avatar/:filename
 */
router.delete('/delete-avatar/:filename', (req, res) => {
  try {
    const { filename } = req.params
    const filePath = path.join(avatarUploadRoot, filename)
    
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath)
      res.json({
        success: true,
        message: '头像删除成功'
      })
    } else {
      res.status(404).json({
        success: false,
        message: '文件不存在'
      })
    }
  } catch (error) {
    console.error('删除头像失败:', error)
    res.status(500).json({
      success: false,
      message: '删除头像失败',
      error: error.message
    })
  }
})

// 错误处理中间件
router.use((error, req, res, next) => {
  if (error instanceof multer.MulterError) {
    if (error.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({
        success: false,
        message: '文件大小超过限制，最大支持 2MB'
      })
    }
  }
  
  if (error.message === '只支持 JPG、JPEG、PNG 格式的图片') {
    return res.status(400).json({
      success: false,
      message: error.message
    })
  }
  
  res.status(500).json({
    success: false,
    message: '上传过程中发生错误',
    error: error.message
  })
})

module.exports = router;
